package cn.t.service.device;

import cn.t.constants.CommonConstants;
import cn.t.core.service.ServiceImpl;
import cn.t.enums.device.SizeEnum;
import cn.t.model.device.AngleDO;
import cn.t.model.device.CargowayDO;
import cn.t.model.device.DeviceDO;
import cn.t.repository.device.CargowayRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 货道表(Cargoway)领域服务
 *
 * @author t
 * @since 2024-05-24 10:19:11
 */
@Slf4j
@Service
@AllArgsConstructor
public class CargowayService extends ServiceImpl<CargowayDO, CargowayRepository> {

    // 批量添加货道
    public void batchSave(List<CargowayDO> cargowayDOS) {
        this.repository.addOrUpdateBatch(cargowayDOS);
    }

    public CargowayDO buildCargowayDO(long deviceId, Integer incrementNum, int line, int column) {
        CargowayDO cargowayDO = new CargowayDO();
        cargowayDO.setLineNum(line +1);
        cargowayDO.setColumnNum(column +1);
        cargowayDO.setDeviceId(deviceId);
        cargowayDO.setCargowayNo(incrementNum);
        cargowayDO.setGravityScaleNo(incrementNum);
        cargowayDO.setDoorLockNo(String.valueOf(line) + column);
        cargowayDO.setMotorNo(String.valueOf(line) + column);
        cargowayDO.setLedNo(incrementNum);
        return cargowayDO;
    }

    public void updateCargoway(Long cargowayId, Integer cargowayVol) {
        CargowayDO cargowayDO = new CargowayDO();
        cargowayDO.setId(cargowayId);
        cargowayDO.setCargowayVol(cargowayVol);
        this.update(cargowayDO);
    }

    public List<CargowayDO> getCargowayList(List<Long> deviceIds) {
        CargowayDO queryParams = new CargowayDO();
        queryParams.setDeviceIds(deviceIds);
        return this.findByModel(queryParams, CommonConstants.ZERO, Integer.MAX_VALUE, null, null);
    }

    public List<List<String>> convertToExcelRows(List<String> inputList) {

        int rows = (inputList.size() + CommonConstants.CARGOWAY_LABEL - 1) / CommonConstants.CARGOWAY_LABEL;
        List<List<String>> excelRows = new ArrayList<>();
        int pageSize = CommonConstants.CARGOWAY_LABEL;
        for (int i = 0; i < rows; i++) {
            int start = i * CommonConstants.CARGOWAY_LABEL;
            List<String> news = inputList.stream().skip(start).limit(pageSize).collect(Collectors.toList());
            if (news.size() < CommonConstants.CARGOWAY_LABEL) {
                List<String> strings = Collections.nCopies(CommonConstants.CARGOWAY_LABEL - news.size(), "");
                news.addAll(strings);
            }

            excelRows.add(news);
        }
        return excelRows;
    }

    public void generateExcel(List<List<String>> data, OutputStream outputStream) {
        if (data == null || data.isEmpty()) {
            throw new IllegalArgumentException("数据不能为空");
        }

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("标签");
            float desiredRowHeightInPoints = CommonConstants.CARGOWAY_LABEL_HEIGHT;

            // 创建单元格样式
            CellStyle centerCellStyle = workbook.createCellStyle();
            // 设置单元格内容居中
            centerCellStyle.setAlignment(HorizontalAlignment.LEFT);
            // 设置单元格内容垂直居中
            centerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            centerCellStyle.setWrapText(true);
            //设置字体大小
            Font font = workbook.createFont();
            // 设置字体大小（单位为磅）
            font.setFontHeightInPoints((short) 16);
            //字体加粗
            font.setBold(true);
            centerCellStyle.setFont(font);
            // 设置所有列的宽度
            for (int colIndex = 0; colIndex < data.get(0).size(); colIndex++) {
                sheet.setColumnWidth(colIndex, CommonConstants.CARGOWAY_LABEL_WIDTH);
            }

            // 添加数据并设置内容居中
            for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
                List<String> rowData = data.get(rowIndex);
                Row row = sheet.createRow(rowIndex);
                row.setHeightInPoints(desiredRowHeightInPoints);

                for (int colIndex = 0; colIndex < rowData.size(); colIndex++) {
                    //边框加粗
                    centerCellStyle.setBorderBottom(BorderStyle.THICK);
                    centerCellStyle.setBorderLeft(BorderStyle.THICK);
                    centerCellStyle.setBorderRight(BorderStyle.THICK);
                    centerCellStyle.setBorderTop(BorderStyle.THICK);
                    String cellData = rowData.get(colIndex);
                    Cell cell = row.createCell(colIndex);
                    cell.setCellValue(cellData);
                    cell.setCellStyle(centerCellStyle);
                }
            }

            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            // 或者可以选择更合适的异常处理方式
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Map<Long, List<CargowayDO>> getCargowayMap(List<DeviceDO> devices) {
        List<Long> deviceIds = devices.stream().map(DeviceDO::getId).collect(Collectors.toList());
        List<CargowayDO> cargowayDOS = this.getCargowayList(deviceIds);

        return cargowayDOS.stream().collect(Collectors.groupingBy(CargowayDO::getDeviceId));
    }

    public Integer buildRotatingCabinetsCargowayDO(long deviceId, Integer incrementNum,
                                                Integer storeyNum, Integer cargowayNum,
                                                List<CargowayDO> cargowayDOS, Map<Integer, List<AngleDO>> angleMap) {
        Map<Integer, Long> result = angleMap.get(cargowayNum).stream()
                .collect(Collectors.toMap(
                        AngleDO::getCargowayNo,
                        AngleDO::getAngle,
                        (existing, replacement) -> existing));
        for (int i = 1; i <= cargowayNum; i++) {
            CargowayDO cargowayDO = new CargowayDO();
            cargowayDO.setLineNum(storeyNum);
            cargowayDO.setColumnNum(i);
            cargowayDO.setDeviceId(deviceId);
            cargowayDO.setCargowayNo(incrementNum);
            cargowayDO.setGravityScaleNo(incrementNum);
            cargowayDO.setLedNo(incrementNum);
            cargowayDO.setMotorNo(String.valueOf(incrementNum));
            cargowayDO.setDoorLockNo(String.valueOf(incrementNum));
            cargowayDO.setSize(SizeEnum.SIZE_S.getCode());
            cargowayDO.setAngle(result.get(i));
            cargowayDO.setType(CommonConstants.ONE);
            cargowayDOS.add(cargowayDO);
            incrementNum++;
        }
        return incrementNum;
    }

}
